package br.com.consultsystems.persistencia.impl.financeiro;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.consultsystems.dominio.financeiro.Conta;
import br.com.consultsystems.persistencia.spec.AbstractAdministradoraRepository;
import br.com.consultsystems.persistencia.spec.financeiro.ContaPersistencia;

@Stateless(name = "contaPersistencia")
public class ContaPersistenciaImpl extends
		AbstractAdministradoraRepository<Conta> implements
		ContaPersistencia {

	protected ContaPersistenciaImpl() {
		super(Conta.class);
	}

	@Override
	public List<Conta> retrieveAll() {
		return retrieveByCriteria(null);
	}

	@Override
	public List<Conta> retrieveByFilter(String nomeCondominio) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Conta> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Conta> root = createRoot(criteriaQuery);
		
		/* Repository -> Apenas pesquias as informações no banco de dados
		 * Filtro por codigo */
		final Path<String> pathCondominio = root.get("condominio").get("nome");
		final Predicate predicateCondiminio = criteriaBuilder.like(pathCondominio, "%"+ nomeCondominio +"%");
		criteriaQuery.where(predicateCondiminio);
		
		final TypedQuery<Conta> typedQuery = em.createQuery(criteriaQuery);
		return typedQuery.getResultList();
	}
	
	@Override
	public List<Conta> retrieveByCondominio(Long idCondominio)
			throws Exception {
		
		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Conta> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Conta> root = createRoot(criteriaQuery);

		final Path<Long> pathId = root.get("condominio").get("id");
		final Predicate predicateId = criteriaBuilder.equal(pathId, idCondominio);

		criteriaQuery.where(predicateId);

		final TypedQuery<Conta> typedQuery = em.createQuery(criteriaQuery);
		return typedQuery.getResultList();
	}
	
}
